package com.rtx.wms.std.handler.po.down;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.model.emums.SysNumberType;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.service.CommonService;
import com.rtx.wms.std.po.bean.ApiCarton;
import com.rtx.wms.std.po.bean.ApiPo;
import com.rtx.wms.std.po.bean.ApiPodetail;
import com.rtx.wms.std.po.bean.Po;
import com.rtx.wms.std.po.bean.Podetail;
import com.rtx.wms.std.po.bean.RtxCarton;
import com.rtx.wms.std.po.service.ApiPoService;
import com.rtx.wms.std.po.service.PoService;
import com.rtx.wms.std.po.service.PodetailService;
import com.rtx.wms.std.po.service.RtxCartonService;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;

/**
 * 格瑞普 po单创建
 * @author Administrator
 *
 */
@Component
public class PoToWmsHandle {
	
    private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	RtxCartonService rtxCartonService;
	
	@Autowired
	ApiPoService apiPoService;
	
	@Autowired
	PoService poService;
	
	@Autowired
	PodetailService podetailService;
	
	@Autowired
	private CommonService commonService;
	
	@Value("${riswms.po.create}")
	private String riswms_po_create;
	
	/**
	 * PO从中间表写入WMS
	 * @param whseid
	 */
	public void handlerReceiptToWms(){
		//获取中间表未处理成功的订单
		List<ApiPo> list = queryApiPo();
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		for(ApiPo o : list){
			//添加wms入库单
			handelAddToWms(o);
			//更新中间表状态
			updateStatus(o);
		}
	}

	//获取中间表未处理成功的订单
	private List<ApiPo> queryApiPo() {
		LambdaQueryWrapper<ApiPo> qw = Wrappers.lambdaQuery();
		qw.in(ApiPo::getEdiflag, WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG);
		qw.lt(ApiPo::getRtxqueue, WmsConstant.DEFAULT_COUNT);
		return apiPoService.querApipo("ris_edi", qw);
	}
	
	/**
	 * 写入wms
	 * @param o
	 */
	private void handelAddToWms(ApiPo apo) {
		String whseid = "";
		try {
			whseid = apo.getWhseid();
			
			String pokey = commonService.getWmsKey(whseid, SysNumberType.SysNumberType1);
			
			Po po = convertPo(whseid,apo,pokey);
			
			poService.addPoAndDetailAndCarton(apo.getWhseid(), po);
			
			//审核标识是否为1,调用wmsPO单及对应的收货箱数据填充到ASN单中，并完成自动收货并关单
			callWms(pokey,apo);
			
			apo.setEdiflag(WmsConstant.SUCCESS_FLAG);
		} catch (Exception e) {
			logger.error("仓库{}，批次号{}从中间表写入WMS异常",whseid,apo.getBatchid(),e);
			apo.setEdiflag(WmsConstant.FAIL_FLAG);
			apo.setEdimsg(e.getMessage());
		}
	}
	
	private Po convertPo(String whseid,ApiPo apo,String pokey) {
		Po po = new Po();
		BeanUtils.copyProperties(apo, po);
		
		po.setPokey(pokey);
		po.setWhseid(whseid);
		po.setStatus("0");
		po.setStorerkey("GREPOW");
		po.setRtxErptype(apo.getRtxErptype());
		List<Podetail> pdList = new ArrayList<Podetail>();
		
		double openqty = 0d;
		int i = 1;
		for(ApiPodetail apd:apo.getPodetail()) {
			Podetail pd = new Podetail();
			BeanUtils.copyProperties(apd,pd);
			pd.setPokey(pokey);
			pd.setPolinenumber(String.format("%05d", i++));
			pd.setToexamine(apo.getToexamine());
			pd.setRtxqcmark(apo.getRtxqcmark());
			pd.setRtxwerks(apo.getRtxwerks());
			pd.setStorerkey("GREPOW");
			pd.setStatus("0");
			pd.setExternpokey(po.getExternpokey());
			pd.setPackkey("STD");
			pd.setUom("EA");
			pd.setQtyreceived("0");
			pd.setRtx_erpokey(apd.getRtxErpokey());
			openqty += Double.parseDouble(apd.getQtyordered());
			pdList.add(pd);
		}
		po.setOpenqty(openqty+"");
		po.setPodetailList(pdList);
		
		List<RtxCarton> clist = new ArrayList<RtxCarton>(); 
		for(ApiCarton ca:apo.getCarton()) {
			RtxCarton rca = new RtxCarton();
			BeanUtils.copyProperties(ca, rca);
			try {
				SimpleDateFormat df = new SimpleDateFormat();
				df.format("yyyy-MM-dd");
				rca.setRtxpd(df.parse(ca.getRtxpd()));
			} catch (Exception e) {
				logger.error("",e);
			}
			clist.add(rca);
		}
		po.setCartonList(clist);
		
		return po;
		
	}
	
	void callWms(String pokey,ApiPo apo){
		if(!"1".equals(apo.getToexamine())) {
			return;
		}
		String uid = UUID.randomUUID().toString();
		Map<String,String> request = new HashMap<>();
		request.put("pokey", pokey);
		request.put("whseid", apo.getWhseid());
		logger.info("uid-{}-请求PO单及对应的收货箱数据填充到ASN单中，并完成自动收货并关单-{}",uid,JSON.toJSONString(request));
		String result = HttpRequest
				.post(riswms_po_create)
				.body(JSON.toJSONString(request))
				.timeout(30000)
				.execute()
				.body();
		logger.info("uid-{}-响应PO单及对应的收货箱数据填充到ASN单中，并完成自动收货并关单-{}",uid,result);
		JSONObject res = JSON.parseObject(result);
		if(!"200".equals(res.get("returnCode"))) {
			throw new RuntimeException("pokey-"+pokey+"-请求PO单及对应的收货箱数据填充到ASN单中，并完成自动收货并关单失败-"+result);
		}
	}
	
	/**
	 * 更新中间表状态
	 * @param o
	 */
	private void updateStatus(ApiPo o) {
		LambdaUpdateWrapper<ApiPo> update = Wrappers.lambdaUpdate();
		update.eq(ApiPo::getBatchid,o.getBatchid())
		.set(ApiPo::getEdiflag,o.getEdiflag())
		.set(ApiPo::getEdimsg,StrUtil.sub(o.getEdimsg(), 0, 498))
		.set(ApiPo::getRtxqueue,o.getRtxqueue() + 1);
		apiPoService.updateByWrapper("ris_edi",update);
	};
}
